package cn.stylefeng.guns.modular.kehao.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.*;
import cn.stylefeng.guns.modular.basic.model.params.BasicAddressParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicAddressResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicPositionGoods;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicPositionGoodsService;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderOutDetailedParam;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderOutParam;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderOutDetailedService;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderOutService;
import cn.stylefeng.guns.modular.kehao.entity.KhLyOutOrder;
import cn.stylefeng.guns.modular.kehao.mapper.KhLyOutOrderMapper;
import cn.stylefeng.guns.modular.kehao.model.params.KhLyOutOrderParam;
import cn.stylefeng.guns.modular.kehao.model.result.KhLyOutOrderResult;
import cn.stylefeng.guns.modular.kehao.service.KhLyOutOrderService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 可好出库订单 服务实现类
 * </p>
 *
 * @author zzh
 * @since 2025-09-30
 */
@Service
public class KhLyOutOrderServiceImpl extends ServiceImpl<KhLyOutOrderMapper, KhLyOutOrder> implements KhLyOutOrderService {

    @Autowired
    private UserService userService;

    @Autowired
    private HxBasicPositionGoodsService hxBasicPositionGoodsService;

    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private BasicOperateService basicOperateService;

    @Autowired
    private BasicPutgoodsService basicPutgoodsService;

    @Autowired
    private BasicAddressService basicAddressService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private HxOrderOutService hxOrderOutService;

    @Autowired
    private HxOrderOutDetailedService hxOrderOutDetailedService;

    @Override
    public void add(KhLyOutOrderParam param) {
        KhLyOutOrder entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(KhLyOutOrderParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(KhLyOutOrderParam param) {
        KhLyOutOrder oldEntity = getOldEntity(param);
        KhLyOutOrder newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public KhLyOutOrderResult findBySpec(KhLyOutOrderParam param) {
        return null;
    }

    @Override
    public List<KhLyOutOrderResult> findListBySpec(KhLyOutOrderParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(KhLyOutOrderParam param, String condition) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param, condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 获取excel数据
     * @param file
     * @param user
     * @return
     */
    @Override
    public ResponseData getExceldata(MultipartFile file, User user) {
        ResponseData data = new ResponseData();
        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            data.setMessage("上传文件格式不正确");
            data.setSuccess(false);
        }

        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        try {
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            Sheet sheet = wb.getSheetAt(0);
            KhLyOutOrder khLyOutOrderAdd;
            List<KhLyOutOrder> khLyOutOrderAddList = new ArrayList<>();
            for (int r = 1; r <= sheet.getLastRowNum() + 1; r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                khLyOutOrderAdd = new KhLyOutOrder();
                // 出库/冲销单号
                String  outOrderNo = getCellValue(row.getCell(0));
                if(ToolUtil.isEmpty(outOrderNo)){
                    continue;
                }
                Integer count = this.lambdaQuery()
                        .eq(KhLyOutOrder::getOutOrderNo, outOrderNo)
                        .count();
                // 已拉取过，跳过该订单
                if(count > 0 ){
                    continue;
                }
                khLyOutOrderAdd.setOutOrderNo(outOrderNo);
                // 订单单号
                String  orderNo = getCellValue(row.getCell(1));
                if(ToolUtil.isNotEmpty(orderNo)){
                    khLyOutOrderAdd.setOrderNo(orderNo);
                }
                // 客户单号
                String  custNo = getCellValue(row.getCell(2));
                if(ToolUtil.isNotEmpty(custNo)){
                    khLyOutOrderAdd.setCustNo(custNo);
                }
                // 商品编码
                String  goodsNo = getCellValue(row.getCell(3));
                if(ToolUtil.isNotEmpty(goodsNo)){
                    khLyOutOrderAdd.setGoodsNo(goodsNo);
                }
                // 商品条码
                String  goodsBarCode = getCellValue(row.getCell(4));
                if(ToolUtil.isNotEmpty(goodsBarCode)){
                    khLyOutOrderAdd.setGoodsBarCode(goodsBarCode);
                }
                // 商品名称
                String  goodsName = getCellValue(row.getCell(5));
                if(ToolUtil.isNotEmpty(goodsName)){
                    khLyOutOrderAdd.setGoodsName(goodsName);
                }
                // 业务类型
                String  bizType = getCellValue(row.getCell(6));
                if(ToolUtil.isNotEmpty(bizType)){
                    khLyOutOrderAdd.setBizType(bizType);
                }
                // 物流模式
                String  tmsMode = getCellValue(row.getCell(7));
                if("直流".equals(tmsMode)){
                   continue;
                }
                if(ToolUtil.isNotEmpty(tmsMode)){
                    khLyOutOrderAdd.setTmsMode(tmsMode);
                }
                // 地区
                String  dq = getCellValue(row.getCell(8));
                if(ToolUtil.isNotEmpty(dq)){
                    khLyOutOrderAdd.setDq(dq);
                }
                // 业态
                String  yt = getCellValue(row.getCell(9));
                if(ToolUtil.isNotEmpty(yt)){
                    khLyOutOrderAdd.setYt(yt);
                }
                // 大区
                String  bq = getCellValue(row.getCell(10));
                if(ToolUtil.isNotEmpty(bq)){
                    khLyOutOrderAdd.setBq(bq);
                }
                // 区本
                String  qb = getCellValue(row.getCell(11));
                if(ToolUtil.isNotEmpty(qb)){
                    khLyOutOrderAdd.setQb(qb);
                }
                // 单据类型
                String  billType = getCellValue(row.getCell(12));
                if(ToolUtil.isNotEmpty(billType)){
                    khLyOutOrderAdd.setBillType(billType);
                }
                // 冲销原单
                String  offsetOrderNo = getCellValue(row.getCell(13));
                if(ToolUtil.isNotEmpty(offsetOrderNo)){
                    khLyOutOrderAdd.setOffsetOrderNo(offsetOrderNo);
                }
                // 配送机构
                String  psjg = getCellValue(row.getCell(14));
                if(ToolUtil.isNotEmpty(psjg)){
                    khLyOutOrderAdd.setPsjg(psjg);
                }
                // 配送库存地
                String  pskcd = getCellValue(row.getCell(15));
                if(ToolUtil.isNotEmpty(pskcd)){
                    khLyOutOrderAdd.setPskcd(pskcd);
                }
                // 一级类目
                String  category1 = getCellValue(row.getCell(16));
                if(ToolUtil.isNotEmpty(category1)){
                    khLyOutOrderAdd.setCategory1(category1);
                }
                // 二级类目
                String  category2 = getCellValue(row.getCell(17));
                if(ToolUtil.isNotEmpty(category2)){
                    khLyOutOrderAdd.setCategory2(category2);
                }
                // 三级类目
                String  category3 = getCellValue(row.getCell(18));
                if(ToolUtil.isNotEmpty(category3)){
                    khLyOutOrderAdd.setCategory3(category3);
                }
                // 收货机构
                String  shjg = getCellValue(row.getCell(19));
                if(ToolUtil.isNotEmpty(shjg)){
                    khLyOutOrderAdd.setShjg(shjg);
                }

//                // 收货机构
//                String  shjgdz = getCellValue(row.getCell(20));
//                if(ToolUtil.isNotEmpty(shjgdz)){
//                    khLyOutOrderAdd.setShjgdz(shjgdz);
//                }
                // 出库数量
                String  outNum = getCellValue(row.getCell(20));
                if(ToolUtil.isNotEmpty(outNum)){
                    khLyOutOrderAdd.setOutNum(new BigDecimal(outNum));
                }
                // 冲销数量
                String  offsetOutNum = getCellValue(row.getCell(21));
                if(ToolUtil.isNotEmpty(offsetOutNum)){
                    khLyOutOrderAdd.setOffsetOutNum(new BigDecimal(offsetOutNum));
                }
                // 出库/冲销数量
                String  outOffsetNum = getCellValue(row.getCell(22));
                if(ToolUtil.isNotEmpty(outOffsetNum)){
                    khLyOutOrderAdd.setOutOffsetNum(new BigDecimal(outOffsetNum));
                }
                // 单位
                String  unit = getCellValue(row.getCell(23));
                if(ToolUtil.isNotEmpty(unit)){
                    khLyOutOrderAdd.setUnit(unit);
                }
                // 核算主体
                String  acctEnt = getCellValue(row.getCell(24));
                if(ToolUtil.isNotEmpty(acctEnt)){
                    khLyOutOrderAdd.setAcctEnt(acctEnt);
                }
                // 成本单价
                String  unitCost = getCellValue(row.getCell(25));
                if(ToolUtil.isNotEmpty(unitCost)){
                    khLyOutOrderAdd.setUnitCost(new BigDecimal(unitCost));
                }
                // 成本金额
                String  costAmt = getCellValue(row.getCell(26));
                if(ToolUtil.isNotEmpty(costAmt)){
                    khLyOutOrderAdd.setCostAmt(new BigDecimal(costAmt));
                }
                // 未税成本单价
                String  untaxUnitCost = getCellValue(row.getCell(27));
                if(ToolUtil.isNotEmpty(untaxUnitCost)){
                    khLyOutOrderAdd.setUntaxUnitCost(new BigDecimal(untaxUnitCost));
                }
                // 未税成本金额
                String  untaxCostAmt = getCellValue(row.getCell(28));
                if(ToolUtil.isNotEmpty(untaxCostAmt)){
                    khLyOutOrderAdd.setUntaxCostAmt(new BigDecimal(untaxCostAmt));
                }
                // 作业人
                String  operator = getCellValue(row.getCell(29));
                if(ToolUtil.isNotEmpty(operator)){
                    khLyOutOrderAdd.setOperator(operator);
                }
                // 作业时间
                String  opTime = getCellValue(row.getCell(30));
                if(ToolUtil.isNotEmpty(opTime)){
                    khLyOutOrderAdd.setOpTime(opTime);
                }
                // 作业系统
                String  opSys = getCellValue(row.getCell(31));
                if(ToolUtil.isNotEmpty(opSys)){
                    khLyOutOrderAdd.setOpSys(opSys);
                }
                // 是否销售
                String  sellFlag = getCellValue(row.getCell(32));
                if(ToolUtil.isNotEmpty(sellFlag)){
                    khLyOutOrderAdd.setSellFlag(sellFlag);
                }
                // 是否跨公司
                String  crossCompanyFlag = getCellValue(row.getCell(33));
                if(ToolUtil.isNotEmpty(crossCompanyFlag)){
                    khLyOutOrderAdd.setCrossCompanyFlag(crossCompanyFlag);
                }

                khLyOutOrderAdd.setCreateUser(user.getAccount());
                khLyOutOrderAdd.setCreateTime(new Date());
                khLyOutOrderAddList.add(khLyOutOrderAdd);
            }

            if(ToolUtil.isNotEmpty(khLyOutOrderAddList) && khLyOutOrderAddList.size() > 0){
                this.saveBatch(khLyOutOrderAddList);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseData.error(e.getMessage());
        }
        return ResponseData.success();
    }

    @Override
    @Transactional
    public ResponseData btnSubmit(String ids, User user) {
        if (ToolUtil.isEmpty(ids)) {
            return ResponseData.error("请选择提交数据数据");
        }

        List<String> list = ListUtil.of(ids.split(","));
        List<KhLyOutOrder> khLyOutOrderList = this.lambdaQuery()
                .in(KhLyOutOrder::getId, list)
                .list();
        if (ToolUtil.isEmpty(khLyOutOrderList)) {
            return ResponseData.error("请选择提交数据数据");
        }

        // 客户信息
        BasicCustomer r = basicCustomerService.getById(148);
        //项目信息
        BasicOperate basicOperate = basicOperateService.getById(r.getCustomerOperateId());//分公司信息
        // 装车单位
        BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
        basicPutgoodsParam.setUnitCategory("发货");
        basicPutgoodsParam.setDeptId(r.getDeptId());
        BasicPutgoodsResult fhPutgoods = basicPutgoodsService.findBySpec(basicPutgoodsParam, Long.parseLong(r.getCustomerOperateId().toString()));//发货
        if (fhPutgoods == null) {
            return ResponseData.error("发货单位不存在，请先维护！");
        }
        BasicAddressParam fhAddressParam = new BasicAddressParam();
        fhAddressParam.setPutgoodsId(Long.parseLong(fhPutgoods.getId().toString()));
        BasicAddressResult fhAddress = basicAddressService.findBySpec(fhAddressParam);
        if (fhAddress == null) {
            return ResponseData.error("发货单位地址不存在，请先维护！");
        }
        // 根据仓库ID获取库位绑定信息。
        List<Integer> warehouseIdList = ListUtil.of(123, 124, 125, 126);
        List<HxBasicPositionGoods> hxBasicPositionGoodsList = hxBasicPositionGoodsService.lambdaQuery()
                .in(HxBasicPositionGoods::getWarehouseId, warehouseIdList)
                .list();

        Map<String,HxBasicPositionGoods> goodsPositionMap = new HashMap<>();
        for(HxBasicPositionGoods obj : hxBasicPositionGoodsList){
            goodsPositionMap.put(obj.getGoodsNumber(),obj);
        }
        //临沂仓 门店单位编码
        Map<String,String> mdMap = new HashMap<>();
        Set<Integer> goodsIdList = new HashSet<>();
        Set<String> warehouseSet = new HashSet<>();
        // 检查商品是否已绑定拣货位，若无拣货位，提示先绑定拣货位
        Set<String> errGoodsSet = new HashSet<>();
        for(KhLyOutOrder obj : khLyOutOrderList){
            if(goodsPositionMap.get(obj.getGoodsNo()) == null){
                errGoodsSet.add(obj.getGoodsNo());
            }else{
                goodsIdList.add(goodsPositionMap.get(obj.getGoodsNo()).getGoodsId().intValue());
            }
            if(ToolUtil.isNotEmpty(obj.getShjg())){
                String putGoosCode = StringUtils.substringBefore(obj.getShjg(),"|");
                String putGoosName = StringUtils.substringAfter(obj.getShjg(),"|");
                mdMap.put(putGoosCode,putGoosName);
            }else{
                mdMap.put("LYC000","临沂仓");
            }
            String psJgBm = StringUtils.substringBefore(obj.getPsjg(),"|");
            warehouseSet.add(psJgBm);
        }
        if(errGoodsSet.size() > 0){
            StringBuffer errStr = new StringBuffer();
            for(String errStrObj : errGoodsSet){
                if(errStr.length() < 1){
                    errStr.append(errStrObj);
                }else{
                    errStr.append(",").append(errStrObj);
                }
            }
            return ResponseData.error("商品["+errStr.toString()+"]未绑定拣货位，请先绑定拣货位");
        }
        // 查询对应仓库信息
        List<BasicWarehouse> basicWarehouseList = basicWarehouseService.lambdaQuery()
//                .in(BasicWarehouse::getWarehouseNumber, warehouseSet)
                .eq(BasicWarehouse::getWarehouseOperateId, r.getCustomerOperateId())
                .list();

        Map<String,BasicWarehouse> basicWarehouseMap = new HashMap<>();
        for(BasicWarehouse obj : basicWarehouseList){
            basicWarehouseMap.put(obj.getWarehouseNumber(),obj);
        }

        // 仓库对照
        Map<String,String> warehouseRef = new HashMap<>();
        warehouseRef.put("1201","DC06");
        warehouseRef.put("1208","DC06");
        warehouseRef.put("1202","DC07");
        warehouseRef.put("1205","DC07");
        warehouseRef.put("1209","DC07");
        warehouseRef.put("1207","DC08");
        warehouseRef.put("1206","DC09");

        // 获取发货地址信息。 若没有提示先创建发货单位及地址信息
        List<BasicPutgoods> basicPutgoodsList = basicPutgoodsService.lambdaQuery()
                .in(BasicPutgoods::getUnitNumber, mdMap.keySet())
                .eq(BasicPutgoods::getPutgoodsCustomerId, 148)
                .list();
        Map<String,BasicPutgoods> basicPutgoodsMap = new HashMap<>();
        for(BasicPutgoods obj : basicPutgoodsList){
            basicPutgoodsMap.put(obj.getUnitNumber(),obj);
        }
        // 循环检查并创建收货门店地址信息。
        BasicPutgoods bpgp3;
        for(String key : mdMap.keySet()){
            // 无对应门店信息，新增
            if(ToolUtil.isEmpty(basicPutgoodsMap.get(key))){
                bpgp3 = new BasicPutgoods();
                bpgp3.setPutgoodsOperateName(r.getCustomerName());//客户名称
                bpgp3.setUnitNumber(key);
                bpgp3.setPutgoodsName(mdMap.get(key));
                bpgp3.setDeliverId(r.getDeliverId());
                bpgp3.setDeptId(r.getDeptId());
                bpgp3.setXlbClientId(StringUtils.substring(key,3));
                bpgp3.setPutgoodsCustomerId(r.getId());
                bpgp3.setUnitType("门店");
                basicPutgoodsService.save(bpgp3);
                BasicAddress bap3 = new BasicAddress();
                bap3.setPutgoodsName(mdMap.get(key));
                bap3.setPutgoodsId(Long.parseLong(bpgp3.getId().toString()));
                bap3.setAddress(mdMap.get(key));
                bap3.setLongitude("0");
                bap3.setLatitude("0");
                bap3.setSwitchWl("1");
                bap3.setSwitchBj("1500");//提货围栏半径 默认100米
                bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
                basicAddressService.save(bap3);
                basicPutgoodsMap.put(key,bpgp3);
            }
        }

        // 查询涉及的货品信息
        List<HxBasicGoods> hxBasicGoodsList = hxBasicGoodsService.lambdaQuery()
                .in(HxBasicGoods::getId, goodsIdList)
                .list();
        Map<String,HxBasicGoods> hxBasicGoodsMap = new HashMap<>();
        for(HxBasicGoods obj : hxBasicGoodsList){
            hxBasicGoodsMap.put(obj.getGoodsNumber(),obj);
        }

        Map<String,HxOrderOutParam> addHxOrderOutParam = new HashMap<>();
        HxOrderOutDetailedParam addHxOrderOutDetailedParam;
        List<HxOrderOutDetailedParam> addHxOrderOutDetailedParamList;

        List<Long> khLyOutOrderIdList = new ArrayList<>();
        for(KhLyOutOrder obj : khLyOutOrderList){
            khLyOutOrderIdList.add(obj.getId());
            String orderOutNumber = "LYC-"+obj.getOutOrderNo();

            // 添加明细
            addHxOrderOutDetailedParam = new HxOrderOutDetailedParam();
            //创建订单明细
            addHxOrderOutDetailedParam.setOrderOutNumber(orderOutNumber);
            addHxOrderOutDetailedParam.setGoodsId(hxBasicGoodsMap.get(obj.getGoodsNo()).getId().longValue());
            addHxOrderOutDetailedParam.setGoodsName(hxBasicGoodsMap.get(obj.getGoodsNo()).getGoodsName());
            addHxOrderOutDetailedParam.setGoodsNumber(obj.getGoodsNo());
            addHxOrderOutDetailedParam.setGoodsPcode69(hxBasicGoodsMap.get(obj.getGoodsNo()).getGoodsPcode69());
            addHxOrderOutDetailedParam.setGoodsXcode69(hxBasicGoodsMap.get(obj.getGoodsNo()).getGoodsXcode69());
            addHxOrderOutDetailedParam.setGoodsHcode69(hxBasicGoodsMap.get(obj.getGoodsNo()).getGoodsHcode69());
            addHxOrderOutDetailedParam.setGoodsSpecs(hxBasicGoodsMap.get(obj.getGoodsNo()).getGoodsSpecs());
            addHxOrderOutDetailedParam.setDismantlingParts(hxBasicGoodsMap.get(obj.getGoodsNo()).getDismantlingParts());
            addHxOrderOutDetailedParam.setPsNum(String.valueOf(obj.getOutNum()));
            addHxOrderOutDetailedParam.setUnit(obj.getUnit());
            addHxOrderOutDetailedParam.setRate(hxBasicGoodsMap.get(obj.getGoodsNo()).getPsRate());
            addHxOrderOutDetailedParam.setJibenUnit(hxBasicGoodsMap.get(obj.getGoodsNo()).getJibenUnit());
            addHxOrderOutDetailedParam.setJibenNum(String.valueOf(obj.getOutNum().multiply(new BigDecimal(hxBasicGoodsMap.get(obj.getGoodsNo()).getPsRate())).setScale(2, BigDecimal.ROUND_HALF_DOWN)));
            addHxOrderOutDetailedParam.setGoodsWeight(hxBasicGoodsMap.get(obj.getGoodsNo()).getGoodsWeight());
            BigDecimal outWeight = new BigDecimal(addHxOrderOutDetailedParam.getGoodsWeight()).multiply(new BigDecimal(addHxOrderOutDetailedParam.getJibenNum())).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            addHxOrderOutDetailedParam.setOutWeight(String.valueOf(outWeight));
            addHxOrderOutDetailedParam.setGoodsVolume(hxBasicGoodsMap.get(obj.getGoodsNo()).getGoodsVolume());
            BigDecimal outVolume = new BigDecimal(addHxOrderOutDetailedParam.getGoodsVolume()).multiply(new BigDecimal(addHxOrderOutDetailedParam.getJibenNum())).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            addHxOrderOutDetailedParam.setOutVolume(String.valueOf(outVolume));
            addHxOrderOutDetailedParam.setGoodsPrice(hxBasicGoodsMap.get(obj.getGoodsNo()).getGoodsChargingPs());
            BigDecimal outMoney = new BigDecimal(addHxOrderOutDetailedParam.getGoodsPrice()).multiply(new BigDecimal(addHxOrderOutDetailedParam.getJibenNum())).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            addHxOrderOutDetailedParam.setOutMoney(String.valueOf(outMoney));

            if(ToolUtil.isEmpty(addHxOrderOutParam.get(orderOutNumber))){
                // 创建出库订单及明细。
                HxOrderOutParam opp = new HxOrderOutParam();
                opp.setOrderOutNumber(orderOutNumber);//订单号
                //新增出库订单
                opp.setCustomerId(r.getId().longValue());//客户id
                opp.setCustomerName(r.getCustomerName());//客户名称
                opp.setOrderState("待提交");//订单状态
                opp.setXlbSetUnitId(r.getStoreIdXlb());
                opp.setSetUnit(fhPutgoods.getPutgoodsName());//装货单位
                opp.setSetUnitId(Long.parseLong(fhPutgoods.getId().toString()));//装货单位id
                opp.setSetLocation(fhAddress.getAddress());//装货地址
                opp.setSetLocationId(Long.parseLong(fhAddress.getId().toString()));//装货地址id
                opp.setSetPeople(fhAddress.getContacts());//联系人
                opp.setSetTel(fhAddress.getTel());//联系电话
                String psJgBm = StringUtils.substringBefore(obj.getPsjg(),"|");
                String psJgBmWare = warehouseRef.get(psJgBm);
                if(ToolUtil.isNotEmpty(basicWarehouseMap.get(psJgBmWare))){
                    opp.setSetWarehouseId(basicWarehouseMap.get(psJgBmWare).getId().longValue());//仓库id
                    opp.setSetWarehouse(basicWarehouseMap.get(psJgBmWare).getWarehouseName());//仓库名称
                }
                opp.setCreateUserName(user.getName());//制单人名称
                opp.setCreateTime(new Date());
                opp.setDeliverId(r.getDeliverId());//交付id
                opp.setDeptId(r.getDeptId());//部门id

                opp.setPeisongTime(cn.stylefeng.guns.core.util.DateUtil2.getDate());//配送日期
                opp.setOrderType("门店调出");
                opp.setXlbClientId(obj.getOutOrderNo());
                String putGoosCode = StringUtils.substringBefore(obj.getShjg(),"|");
                if(ToolUtil.isNotEmpty(basicPutgoodsMap.get(putGoosCode))){
                    opp.setGetUnit(basicPutgoodsMap.get(putGoosCode).getPutgoodsName());
                    opp.setGetUnitId(basicPutgoodsMap.get(putGoosCode).getId().longValue());
                    BasicAddress basicAddressObj = basicAddressService.lambdaQuery()
                            .eq(BasicAddress::getPutgoodsId, basicPutgoodsMap.get(putGoosCode).getId())
                            .last(" limit 1 ")
                            .one();
                    if(ToolUtil.isNotEmpty(basicAddressObj)){
                        opp.setGetLocationId(basicAddressObj.getId().longValue());//卸货地址id
                        opp.setGetLocation(basicAddressObj.getAddress());//卸货地址
                        opp.setGetPeople(basicAddressObj.getContacts());//联系人
                        opp.setGetTel(basicAddressObj.getTel());//联系电话
                    }
                }
                addHxOrderOutDetailedParamList = new ArrayList<>();
                addHxOrderOutDetailedParamList.add(addHxOrderOutDetailedParam);
                opp.setHxdList(addHxOrderOutDetailedParamList);
                addHxOrderOutParam.put(orderOutNumber,opp);
            }else{
                addHxOrderOutParam.get(orderOutNumber).getHxdList().add(addHxOrderOutDetailedParam);
            }
        }


        // 批量添加
        List<HxOrderOutParam> olist = new ArrayList<HxOrderOutParam>();//批量保存的 出库订单list
        List<HxOrderOutDetailedParam> detailedList = new ArrayList<HxOrderOutDetailedParam>();//批量保存的 订单商品明细list
        for(HxOrderOutParam obj : addHxOrderOutParam.values()){
            olist.add(obj);
            detailedList.addAll(obj.getHxdList());
        }
        hxOrderOutService.saveBatchList(olist);
        hxOrderOutDetailedService.saveBatchList(detailedList);
        // 修改提交状态。
        this.lambdaUpdate()
                .set(KhLyOutOrder::getStat,"已提交")
                .set(KhLyOutOrder::getSubUser,user.getAccount())
                .set(KhLyOutOrder::getSubTime,new Date())
                .in(KhLyOutOrder::getId,khLyOutOrderIdList)
                .update();

        return ResponseData.success();
    }

    private Serializable getKey(KhLyOutOrderParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private KhLyOutOrder getOldEntity(KhLyOutOrderParam param) {
        return this.getById(getKey(param));
    }

    private KhLyOutOrder getEntity(KhLyOutOrderParam param) {
        KhLyOutOrder entity = new KhLyOutOrder();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }

}
